<template>
	<view class="container">
		<view class="uni-padding-wrap uni-common-mt">
			<view class="demo">
				<block v-if="imageSrc">
					<image :src="imageSrc" class="image" mode="widthFix"></image>
				</block>
				<block v-else>
					<view class="uni-hello-addfile" @click="chooseImage">+ 选择图片</view>
				</block>
			</view>
		</view>
	</view>
</template>
<script>
    import commonOnLoad from '../../common/common_on_load.js'; 
	import {
		mapState,
		mapGetters
	} from 'vuex'
	
	export default {
		computed: {
			...mapState(['forcedLogin']),
			...mapGetters(['hasLogin']),
		},
		data() {
			return {
				imageSrc: ''
			}
		},
		onUnload() {
			this.imageSrc = '';
		},
		onLoad(options) {
			commonOnLoad.commonOnLoad(this.$mRoutesConfig.main,options,options.referenceId);//options.referenceId
			setTimeout(() => {
				this.showImg = true;
				// #ifdef H5  
				if (this.$wechat && this.$wechat.isWechat()) {  
					var url = this.$mConfig.baseUrl + "/api/shorturl/" + this.$mConfig.mpAppId + "/index";
					if(this.$store.getters.hasLogin){
						url = url + "?referenceId=" + this.$store.state.userInfo.id;
					}
					 this.$wechat.share({  
						  desc: this.$mConfig.descTxt,  
						  img: this.$mConfig.logoImgUrl,  
						  title:this.$mConfig.loginTitleTxt,  
					},url);  
				}  
				// #endif  
			}, 1000);
			// #ifdef MP
			if (!this.$store.getters.hasLogin ) {
				this.$store.commit("SET_IS_SILENT_LOGIN", true);
				this.silentLogin();
			}
			// #endif
		},
		methods: {
			chooseImage: function() {
				let token = this.$store.state.token;
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album'],
					success: (res) => {
						console.log('chooseImage success, temp path is', res.tempFilePaths[0])
						var imageSrc = res.tempFilePaths[0]
						uni.uploadFile({
							url: this.$mConfig.baseUrl + '/api/health/upload',
							filePath: imageSrc,
							fileType: 'image',
							name: 'file',
							header: {
								"X-Nideshop-Token":token,
							},
							success: (res) => {
								console.log('uploadImage success, res is:', res)
								uni.showToast({
									title: '上传成功',
									icon: 'success',
									duration: 1000
								})
								this.imageSrc = imageSrc
							},
							fail: (err) => {
								console.log('uploadImage fail', err);
								uni.showModal({
									content: err.errMsg,
									showCancel: false
								});
							}
						});
					},
					fail: (err) => {
						console.log('chooseImage fail', err)
					}
				})
			}
		},
	}
</script>

<style lang="scss">
	.image {
		width: 100%;
	}
	
	.demo {
		background: #FFF;
		padding: 50upx;
	}
</style>
